package io.xxx.omni.osc.sdk

import com.alibaba.fastjson.JSONObject
import io.xxx.omni.osc.domain.Store
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import org.springframework.web.util.UriComponentsBuilder
import java.util.*

@Component
class TxhjClient {

    @Autowired
    private lateinit var restTemplate: RestTemplate

    private val httpUrl = "https://qy.sr.qq.com/openapi/v1"

    fun execute(store: Store, path: String, request: Map<String, Any>): JSONObject {
        val authorization = store.authorization
        val signMap = TreeMap(request)
        signMap["requestId"] = UUID.randomUUID().toString().replace("-".toRegex(), "")
        signMap["appId"] = authorization["appId"]
        signMap["timestamp"] = System.currentTimeMillis()
        signMap["nonceStr"] = DigestUtils.md5Hex(signMap["timestamp"].toString()).substring(4, 10)
        val builder = StringBuilder()
            .append(signMap.entries.joinToString("&"))
            .append("&").append("appSecret").append("=").append(authorization["appSecret"])
        val sign = DigestUtils.md5Hex(builder.toString()).uppercase()
        val url = UriComponentsBuilder
            .fromHttpUrl(httpUrl)
            .path(path)
            .toUriString()
        signMap["sign"] = sign
        val response = restTemplate.postForEntity(url, signMap, JSONObject::class.java).body!!
        return response
    }
}